package com.vehicle.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.vehicle.bean.DataGridView;
import com.vehicle.mapper.RoleMapper;
import com.vehicle.pojo.Role;
import com.vehicle.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Repository
public class RoleServiceImp implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role findRoleByRid(Integer rid) {
        return roleMapper.selectRoleByRid(rid);
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public DataGridView findRoleByPage(Role role) {
        Page<Object> page = PageHelper.startPage(role.getPage(), role.getLimit());
        List<Role> roles=roleMapper.selectRoleByPage(role);
        DataGridView dataGridView=new DataGridView();
        dataGridView.setCount(page.getTotal());
        dataGridView.setData(roles);
        return dataGridView;
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public DataGridView findRoleByUid(Integer uid) {
        //查询所有role
        List<Role> roles=roleMapper.selectRoles();
        //根据id查询
        List<Role> roleByUser=roleMapper.selectRolesByUid(uid);
        List<Role> roleVos=new ArrayList<>();
        for (Role role:roles) {
            Role roleVo=new Role();
            roleVo.setRid(role.getRid());
            roleVo.setRname(role.getRname());
            for (Role r:roleByUser) {
                if (role.getRid()==r.getRid()){
                    //如果相同就被选中s
                    roleVo.LAY_CHECKED=true;
                }
            }

            roleVos.add(roleVo);
        }
        DataGridView dataGridView=new DataGridView();
        dataGridView.setData(roleVos);
        return dataGridView;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void assignPermission(Integer rid, Integer[] pids) {
        roleMapper.deletePRByRid(rid);
        if(pids!=null&&pids.length>0){
            for (Integer pid:pids
                 ) {
                roleMapper.insertPR(rid,pid);
            }
        }
    }

    @Override
    public void addRole(Role role) {
        roleMapper.insertRole(role);
    }
}
